package academic.ui.client.presenter;


import academic.ui.client.CustomerServiceAsync;
import academic.ui.client.event.LoggedInEvent;
import academic.ui.client.jquery.JQuery;
import academic.ui.client.place.Tokens;
import academic.ui.client.rules.Rules;
import academic.ui.client.widgets.tools.Overlay;
import ecommerce.soco.shared.GWT_Customer;


import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasText;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;

public class LoginPresenter extends Presenter<LoginPresenter.MyView,LoginPresenter.MyProxy>
{

	private final CustomerServiceAsync service;
	
	
	@Inject 
	public LoginPresenter(EventBus eventBus, MyView view, MyProxy proxy,CustomerServiceAsync service) {
		super(eventBus, view, proxy);
		this.service = service;
	}

	@ProxyStandard	
	@NameToken(Tokens.login)
	public interface MyProxy extends ProxyPlace<LoginPresenter>{

	}

	
	public interface MyView extends View {

		void setup();

		HasClickHandlers getSignIn();

		HasClickHandlers register();

		void updateForRegistration();
		
		Boolean checkSignInRules();

		void setLoginError(String string);

		HasClickHandlers getSignInLink();

		void updateForSignIn();

		HasClickHandlers getRegisterButton();

		boolean checkRegistrationRules();

		GWT_Customer getCustomer();

		HasText getLoginEmail();

		HasText getLoginPasswd();

		HasClickHandlers forgotPasswd();

		void updateForForgotPassword();

		HasClickHandlers cancelForgotPass();

		HasClickHandlers forgotPassButton();

		boolean checkForgotPasswordRules();

		HasText getRecoverPassEmail();

		void updatePostForgotPass();

		void setupLoginFromFB(String email);

		HasClickHandlers cancelSyncLink();

		HasClickHandlers submitSyncProfile();
	}
	
	@Override
	public void onReveal() {
		super.onReveal();
		Log.debug("LoginPresenter onReveal");
		if(email!=null && !"".equals(email))
			getView().setupLoginFromFB(email);
		else
			getView().setup();
	}
	
	private String selector;
	private String email;
	
	@Override
	public void onBind() {
		super.onBind();
		Log.debug("LoginPresenter onBind");
		registerHandler(getView().getSignIn().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				
				if(!getView().checkSignInRules())
					JQuery.fadeInErrors();
				else
					service.login(getView().getLoginEmail().getText(),getView().getLoginPasswd().getText(),new AsyncCallback<Boolean>() {
	
						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							
						}
	
						@Override
						public void onSuccess(Boolean result) {
							if(result) {
								onHide();
								Log.debug("successful login");
								LoggedInEvent.fire(getEventBus());
							}
							else
							{//login was not successful...throw an error
								getView().setLoginError("Email Address And Password Combination not found.");
							}
						}
						
					});
					
			}
			
		}));
		
		
		registerHandler(getView().register().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				getView().updateForRegistration();
			}
			
		}));
		
		registerHandler(getView().getSignInLink().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				getView().updateForSignIn();
			}
			
		}));
		
		registerHandler(getView().getRegisterButton().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if(!getView().checkRegistrationRules())
					Log.debug("display errors");
				else
					service.registerCustomer(getView().getCustomer(), /*attempt to login if customer exists*/false, new AsyncCallback<Integer>() {

						@Override
						public void onFailure(Throwable caught) {
						}

						@Override
						public void onSuccess(Integer result) {
							if(result==Rules.SUCCESS)
								onHide();
							else if(result == Rules.LOGIN_ERROR_USER_NOT_FOUND)
							{//login was not successful...throw an error
								getView().setLoginError("Email Address And Password Combination not found.");
							}
							else if(result==Rules.REGISTER_ERROR_USER_EXISTS)
							{//user already exists
								getView().setLoginError("Email Address already exists.");
							}
						}
						
					});
			}
			
		}));
		
		registerHandler(getView().forgotPasswd().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				getView().updateForForgotPassword();
			}
			
		}));
		
		registerHandler(getView().cancelForgotPass().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				getView().updateForSignIn();
			}
			
		}));
		
		registerHandler(getView().cancelSyncLink().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				onHide();
			}
			
		}));
		
		registerHandler(getView().forgotPassButton().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if(!getView().checkForgotPasswordRules())
					JQuery.fadeInErrors();
				else
				{
					service.emailPasswordIfValid(getView().getRecoverPassEmail().getText(), new AsyncCallback<Boolean>() {

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							
						}

						@Override
						public void onSuccess(Boolean result) {
								getView().updatePostForgotPass();
						}
						
					});
				}
			}
			
		}));
		
		registerHandler(getView().submitSyncProfile().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if(!getView().checkSignInRules())
					JQuery.fadeInErrors();
				else
					service.login(getView().getLoginEmail().getText(),getView().getLoginPasswd().getText(),new AsyncCallback<Boolean>() {
	
						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							
						}
	
						@Override
						public void onSuccess(Boolean result) {
							if(result) {
								onHide();
								LoggedInEvent.fire(getEventBus());
							}
							else
							{//login was not successful...throw an error
								getView().setLoginError("Email Address And Password Combination not found.");
							}
						}
						
					});
					
			}
			
		}));
		
	}
    
	@Override
	protected void revealInParent() {
		RevealContentEvent.fire(this, AppPresenter.slot, this);
		Log.debug("LoginPresenter revealInParent");
	}
	
	@Override
	public void onReset() {
		super.onReset();
		
		
		DeferredCommand.addCommand(new Command() {

			@Override
			public void execute() {
				Log.debug("LoginPresenter onReset DeferredCommand");
				Overlay.initLink("#"+selector);
			}
			
		});		
		Log.debug("LoginPresenter onReset");
	}
	
	@Override
	public void prepareFromRequest(PlaceRequest request) {
		selector = request.getParameter("selector", null);
		email = request.getParameter("email", null);
	}
	
	@Override
	public void onHide() {
		super.onHide();
		Log.debug("LoginPresenter onHide");
		email=null;
		Overlay.hideLink("#"+selector);
	}

}
